package com.cmcc.driver.ui.main

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.location.Location
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Looper
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.DriverDataRepository
import com.cmcc.driver.data.entity.OrderDetail
import com.cmcc.driver.databinding.ActivityOrderInProgressDetailBinding
import com.cmcc.driver.ui.base.BasicActivity
import com.cmcc.driver.ui.dialog.AppAlertDialog
import com.cmcc.driver.ui.dialog.AppInputDialog
import com.cmcc.driver.ui.dialog.AppProgressDialog
import com.cmcc.driver.ui.main.viewmodel.OrderReceiveViewModel
import com.cmcc.driver.util.LocationUtil
import com.cmcc.shared.utils.GPSConverterUtils
import com.cmcc.shared.utils.TextViewUtil.setTextViewByLimit
import com.cmcc.shared.utils.TextViewUtil.setTextViewValue
import com.cmcc.shared.utils.TimeUtils
import com.cmcc.shared.utils.clickWithTrigger
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.maps.android.PolyUtil
import java.text.SimpleDateFormat
import java.util.*


/**
 * Author: jiangxin
 * Date: 2019/11/6
 * Description:接单中
 *
 */
@Route(path = DriverPath.ORDER_IN_PROGRESS_DETAIL)
class OrderInProgressDetailActivity : BasicActivity(), OnMapReadyCallback {


    private var status: Int? = null
    private lateinit var mMap: GoogleMap
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationRequest: LocationRequest
    private lateinit var locationCallback: LocationCallback

    private lateinit var binding: ActivityOrderInProgressDetailBinding

    private var viewModel: OrderReceiveViewModel? = null
    private var orderModel: OrderDetail? = null

    private lateinit var bottomSheetBehavior: BottomSheetBehavior<LinearLayout>
    private var progressDialog: AppProgressDialog? = null

    private var timer: Timer? = null
    private var countDownTimer: CountDownTimer? = null

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap
        isMapReady = true

        mMap.isMyLocationEnabled = true
        mMap.uiSettings.isRotateGesturesEnabled = false
        mMap.uiSettings.isCompassEnabled = true
        mMap.uiSettings.isMyLocationButtonEnabled = false

//        val lat = orderModel?.startCoordinates?.longitude
//        val lng = orderModel?.startCoordinates?.longitude
//        val appointLoc = LatLng(lat ?: 0.0, lng ?: 0.0)
//        googleMap?.moveCamera(CameraUpdateFactory.newLatLngZoom(appointLoc, 15f))

        val loc = LocationUtil.getInstance().getCurrentLoc()
        if (null != loc) {
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15f))
        }

        drawRoutes(googleMap)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        fusedLocationClient =
            LocationServices.getFusedLocationProviderClient(this)

        locationRequest = LocationRequest()
        locationRequest.interval =
            10 * 1000L //请求时间间隔
        locationRequest.fastestInterval =
            1500L//最快时间间隔
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY

        locationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult?) {
                if (locationResult == null) return
                handleLocation(locationResult.lastLocation)
            }
        }


    }

    /**
     * 请求定位服务
     */
    private fun requestLocationService() {
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            requestLocationUpdate()
        }
    }

    /**
     * 请求位置更新
     */
    private fun requestLocationUpdate() {
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.myLooper()
        )
    }

    /**
     * 获取当前位置的回调方法
     */
    private fun handleLocation(lastLocation: Location) {
        mMap.isMyLocationEnabled = true
        mMap.uiSettings.isRotateGesturesEnabled = true
        mMap.uiSettings.isCompassEnabled = true
        mMap.uiSettings.isMyLocationButtonEnabled = true
//        if (status == 1) {
//            mMap.isMyLocationEnabled = true
//            mMap.uiSettings.isRotateGesturesEnabled = false
//            mMap.uiSettings.isCompassEnabled = true
//            mMap.uiSettings.isMyLocationButtonEnabled = false
//        }else {
//            mMap.isMyLocationEnabled = true
//            mMap.uiSettings.isRotateGesturesEnabled = false
//            mMap.uiSettings.isCompassEnabled = false
//            mMap.uiSettings.isMyLocationButtonEnabled = false
//        }
        val latLng = LatLng(lastLocation.latitude, lastLocation.longitude)
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f))

        stopLocationUpdate()
    }

    private fun stopLocationUpdate() {
        fusedLocationClient.removeLocationUpdates(locationCallback)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        binding = DataBindingUtil.setContentView(
            this,
            R.layout.activity_order_in_progress_detail
        )
        binding.appbar.toolbar.setNavigationOnClickListener { finish() }
        ////把地图加到fragment layout去
        val mapFragment = SupportMapFragment()
        supportFragmentManager.beginTransaction().replace(R.id.map, mapFragment).commit();
        mapFragment?.getMapAsync(this)

        bottomSheetBehavior = BottomSheetBehavior.from(binding.progress)

        viewModel = ViewModelProviders.of(this).get(OrderReceiveViewModel::class.java)

        progressDialog = AppProgressDialog(this)

        updateUI()

        // 在onCreate 方法中  让它默认展开状态
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
    }

    private fun updateUI() {
        val orderId: String = intent.getStringExtra("orderId")

        viewModel?.getOrderDetail(orderId)

    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        binding.appbar.toolbar.setNavigationOnClickListener { finish() }

        binding.appbar.title.text = getString(R.string.in_progress_detail_title)
        binding.appbar.profile.visibility = View.GONE

        binding.contactPass.visibility = View.VISIBLE


    }

    override fun initEvent(savedInstanceState: Bundle?) {
        super.initEvent(savedInstanceState)
        binding.appbar.profile.clickWithTrigger {
            ARouter.getInstance().build(DriverPath.DRIVER_PROFILE).navigation()
        }

        binding.navigation.clickWithTrigger {

            val currentLatLng: LatLng? = LocationUtil.getInstance().getCurrentLoc()

            if (null != currentLatLng) {
                val current = convert(currentLatLng)
                val startLatLng = LatLng(current.lat, current.lon)

                var endLatLng: LatLng? = null
                val status = orderModel?.status
                if (status == 1) {
                    val endLat = orderModel?.startCoordinates?.latitude ?: 0.0
                    val endLng = orderModel?.startCoordinates?.longitude ?: 0.0
                    if (endLat != 0.0 && endLng != 0.0) {
                        val end = convert(LatLng(endLat, endLng))
                        endLatLng = LatLng(end.lat, end.lon)
                    }
                } else {
                    val endLat = orderModel?.endCoordinates?.latitude ?: 0.0
                    val endLng = orderModel?.endCoordinates?.longitude ?: 0.0
                    if (endLat != 0.0 && endLng != 0.0) {
                        val end = convert(LatLng(endLat, endLng))
                        endLatLng = LatLng(end.lat, end.lon)
                    }
                }
                if (null != endLatLng) {
                    ARouter.getInstance().build(DriverPath.NAVIGATION)
                        .withParcelable("start_point", startLatLng)
                        .withParcelable("end_point", endLatLng)
                        .navigation()
                }
            }
        }

        binding.locate.clickWithTrigger {
            requestLocationService()
        }


        binding.contactPass.clickWithTrigger {
            AppAlertDialog(this).setContent(getString(R.string.if_you_need_call))
                .setNavigation(getString(R.string.cancel), null)
                .setPositive(getString(R.string.make_sure),
                    View.OnClickListener {
                        val data = Uri.parse("tel:" + orderModel?.passenger?.phone)
                        val intent = Intent(Intent.ACTION_DIAL, data)
                        startActivity(intent)
                    }).show()
        }

        binding.rejectOrder.clickWithTrigger {
            AppAlertDialog(this).setContent(
                getString(
                    R.string.reject_order_send_alert_dialog,
                    viewModel?.orderNumber
                )
            )
                .setNavigation(getString(R.string.cancel), null)
                .setPositive(getString(R.string.make_sure),
                    View.OnClickListener {
                        progressDialog?.show()
                        viewModel?.cancel(orderModel?.id.toString())
                            ?.observe(this, Observer { response ->
                                progressDialog?.dismiss()
                                if (response.code == 200) {
                                    Toast.makeText(
                                        this,
                                        getString(R.string.reject_order_success),
                                        Toast.LENGTH_LONG
                                    ).show()
                                    val intent = Intent(this, OrderInProgressDetailActivity::class.java)
                                    intent.putExtra("id", orderModel?.id ?: "")
                                    setResult(Activity.RESULT_OK, intent)
                                    finish()

                                } else {
                                    Toast.makeText(
                                        this,
                                        getString(R.string.net_work_error_tip2),
                                        Toast.LENGTH_LONG
                                    ).show()
                                }
                            })
                    }).show()
        }

        binding.collapsingLayout.clickWithTrigger {
            when (bottomSheetBehavior.state) {
                BottomSheetBehavior.STATE_COLLAPSED -> {//收起状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED

                    binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                }
                BottomSheetBehavior.STATE_EXPANDED -> {//展开状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED

                    binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                }
            }
        }



        bottomSheetBehavior.setBottomSheetCallback(object : BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (bottomSheetBehavior.state) {
                    BottomSheetBehavior.STATE_COLLAPSED -> {//收起状态
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                    }
                    BottomSheetBehavior.STATE_EXPANDED -> {//展开状态
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                    }

                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {}
        })

        binding.optionsLayout.nextTip1.setOnClickListener {
            val orderStatus: Int? = orderModel?.status ?: -1
            if (orderStatus != -1) {
                when (orderStatus) {
                    0 ->
                        viewModel?.queryOrderProgress()
                    1, 2, 5 ->
                        changeOrder(0, 0.0, 0.0, 0.00, orderStatus.plus(1))
                    3 ->
                        changeOrder(1, 0.0, 0.0, 0.00, 4)
                    4 -> {
                        AppInputDialog(this)
                            .setOnInputListener(
                                orderModel?.bountyFee,
                                object : AppInputDialog.OnInputListener {
                                    override fun onInput(text: String) {
                                        try {
                                            changeOrder(0, 10.0, 10.0, text.toDouble(), 5)
                                        } catch (e: Exception) {
                                        }
                                    }
                                })
                            .show()
                    }
                }
            }
        }


    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initObserver(savedInstanceState: Bundle?) {
        super.initObserver(savedInstanceState)

        viewModel?.orderDetail?.observe(this, Observer { order ->
            hasDrawDriverToStart = false
            hasDrawStartToEnd = false
            if (order == null) {
                orderModel = null
                mMap.clear()
                binding.progress.visibility = View.GONE
                // finish()
            }else {
                orderModel = order
            }

            val status = order.status
            if (status == 6) {
                stopTimer()
                driverMarker?.remove()
                binding.navigation.visibility = View.GONE
            }


            if (status == 0) {
                val isOrderInProgress = isOrderInProgress(status, order.startTime ?: "")
                if (isOrderInProgress) {
                    binding.orderGap.text =
                        getOffTimeGap(this, order.startTime ?: "")

                    countDownTimer = object : CountDownTimer(60 * 60 * 1000L, 1000L) {
                        override fun onTick(millisUntilFinished: Long) {
                            binding.orderGap.text =
                                getOffTimeGap(
                                    this@OrderInProgressDetailActivity,
                                    order.startTime ?: ""
                                )
                        }

                        override fun onFinish() {

                        }
                    }.start()
                } else {
                    binding.orderGap.text =
                        TimeUtils.getOverTimeGap(this, order.startTime ?: "")

                    countDownTimer = object : CountDownTimer(60 * 60 * 1000L, 1000L) {
                        override fun onTick(millisUntilFinished: Long) {
                            binding.orderGap.text =
                                TimeUtils.getOverTimeGap(
                                    this@OrderInProgressDetailActivity,
                                    order.startTime ?: ""
                                )
                        }

                        override fun onFinish() {

                        }
                    }.start()
                }
            } else {
                binding.orderGap.text = ""
                countDownTimer?.cancel()
            }

            binding.directions.directionStart.text = order?.startAddress
            binding.directions.directionEnd.text = order?.endAddress

            setTextViewByLimit(
                binding.textView2,
                order?.type == 1,
                getString(R.string.driver_real_time_order),
                getString(R.string.driver_reservation_order)
            )

            setTextViewByLimit(
                binding.options.textView3,
                order?.type == 1,
                getString(R.string.time_real_time),
                getString(R.string.order_create_time, order?.startTime)
            )

            setTextViewValue(
                this,
                binding.options.tunnel,
                R.string.order_tunnel,
                order?.tunnel?.name,
                getString(R.string.what_ever)
            )


            if (order.bountyFee == null) {
                binding.options.tip.text =
                    resources.getString(R.string.driver_tip) + "HK\$ " + "0.00"
            } else {
                binding.options.tip.text =
                    resources.getString(R.string.driver_tip) + "HK\$ " + order.bountyFee.toString() + ""
            }


            setTextViewValue(
                this,
                binding.options.station,
                R.string.order_station,
                if (order.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") null else order?.stationIndex,
                if (order.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") getString(R.string.what_ever) else null
            )

            setTextViewValue(
                this,
                binding.options.remarks,
                R.string.order_remark,
                order?.remark,
                getString(R.string.none)
            )

            var stepTxt = ""
            when (order.status) {
                0 -> {
                    if (order?.type == 1) {
                        //实时单
                        stepTxt = getString(R.string.driver_order_status0)
                        binding.rejectOrder.visibility = View.VISIBLE
                        binding.contactPass.visibility = View.VISIBLE
                    } else {
                        //预约单
                        stepTxt = getString(R.string.receive_passenger_and_now_start)
                        binding.rejectOrder.visibility = View.VISIBLE
                        binding.contactPass.visibility = View.VISIBLE
                    }

                }
                1 -> {
                    stepTxt = getString(R.string.receive_passenger_and_now_start)
                    binding.rejectOrder.visibility = View.VISIBLE
                    binding.contactPass.visibility = View.VISIBLE
                }
                2 -> {
                    stepTxt = getString(R.string.arrived_destination)
                    binding.rejectOrder.visibility = View.GONE
                    binding.contactPass.visibility = View.GONE
                }
                3 -> {
                    stepTxt = getString(R.string.pay_under_line)
                    binding.rejectOrder.visibility = View.GONE
                    binding.contactPass.visibility = View.GONE
                }
                4 -> {
                    stepTxt = getString(R.string.comfirm_cash)
                    binding.rejectOrder.visibility = View.GONE
                    binding.contactPass.visibility = View.GONE
                }
                5 -> {
                    stepTxt = getString(R.string.complete_trip)
                    binding.rejectOrder.visibility = View.GONE
                    binding.contactPass.visibility = View.GONE
                    //显示金额
                    binding.orderAmount.visibility = View.VISIBLE
                    val plus =
                        orderModel?.bountyFee?.toDouble()?.let {
                            orderModel?.totalAmount?.toDouble()?.plus(
                                it
                            )
                        }
                    binding.orderAmount.text = getString(
                        R.string.driver_order_totle_amount,
                        plus.toString(),
                        orderModel?.bountyFee
                    )
                }
                6 -> {
                    stepTxt = getString(R.string.complete_trip)
                    binding.rejectOrder.visibility = View.GONE
                    binding.contactPass.visibility = View.VISIBLE
                    binding.orderAmount.visibility = View.VISIBLE
                    val plus =
                        orderModel?.bountyFee?.toDouble()?.let {
                            orderModel?.totalAmount?.toDouble()?.plus(
                                it
                            )
                        }
                    binding.orderAmount.text = getString(
                        R.string.driver_order_totle_amount,
                        plus.toString(),
                        orderModel?.bountyFee
                    )
                    binding.optionsLayout.nextTip1.background =
                        this.getDrawable(R.drawable.shape_button_gray_with_corner_x25)
                    finish()
                }
                7 -> {
                    stepTxt = getString(R.string.driver_order_status7)
                    binding.rejectOrder.visibility = View.GONE
                    binding.contactPass.visibility = View.GONE
                    binding.orderAmount.visibility = View.GONE
                    binding.optionsLayout.nextTip1.isEnabled = false
                }
            }

            binding.optionsLayout.nextTip1.text = stepTxt

        })

        viewModel?.nextOrderState?.observe(this, Observer {
            when (it) {
                "loading" -> {
                    binding.optionsLayout.nextTip1.isEnabled = false
                }
                "success" -> {
                    binding.optionsLayout.nextTip1.isEnabled = true
                }
                "error" -> {
                    binding.optionsLayout.nextTip1.isEnabled = true
                }
            }
        })

        viewModel?.resMsg?.observe(this, Observer { resMsg ->
            progressDialog?.dismiss()
            if (null != resMsg) {
                if (resMsg.code == 200) {
                    updateUI()
                    DriverDataRepository.getInstance().hasStatusChange().value = true
                } else {
//                    Toast.makeText(this, resMsg.msg, Toast.LENGTH_LONG).show()
                }
            } else {
                Toast.makeText(this, getString(R.string.operate_failed_retry), Toast.LENGTH_LONG)
                    .show()
            }
        })

        viewModel?.orderDoing?.observe(this, Observer { order ->
            if (order == null || order.status == 0) {
                changeOrder(0, 0.0, 0.0, 0.00, 2)
            } else {
                Toast.makeText(
                    this,
                    getString(R.string.has_order_alert_dialog2),
                    Toast.LENGTH_LONG
                ).show()
            }
        })

    }

    fun getOffTimeGap(context: Context, startTime: String): String {
        var format: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        var startDate: Date = format.parse(startTime)

        var nowTime: Date = Date()
        var timeGap = startDate.time - nowTime.time
        return if (timeGap > 0) {
            TimeUtils.getOffTimeGap(context, startTime)
        } else {
            context.getString(com.cmcc.shared.R.string.book_time_come)
        }
    }

    /**
     * 请求路线
     */
//    private fun queryRoute() {
//        viewModel?.getDirection(
//            orderModel?.startCoordinates?.latitude.toString() + "," + orderModel?.startCoordinates?.longitude,
//            orderModel?.endCoordinates?.latitude.toString() + "," + orderModel?.endCoordinates?.longitude
//        )
//    }

    /**
     * 请求路线
     */
    private fun queryRoute(
        startLatLng: LatLng,
        endLatLng: LatLng
    ) {
        viewModel?.getDirection(
            "${startLatLng.latitude},${startLatLng.longitude}",
            "${endLatLng.latitude},${endLatLng.longitude}"
        )
    }


    private fun changeOrder(
        payMethod: Int, mileageFee: Double,
        durationFee: Double, totalAmount: Double, status: Int
    ) {
        if (!orderModel?.id.isNullOrEmpty()) {
            progressDialog?.show()
            viewModel?.nextOrder(
                orderModel?.id!!,
                payMethod,
                mileageFee,
                durationFee,
                totalAmount,
                status
            )
        }
    }

    /**
     * 绘制路线到谷歌地图
     */
    private fun drawRoutes(map: GoogleMap) {
        viewModel?.direction?.observe(this, Observer {
            val decodedPath = PolyUtil.decode(it) //来源Google Map Util
            val lineOptions = PolylineOptions()
            lineOptions.addAll(decodedPath) //添加路线
            lineOptions.color(Color.parseColor("#0AC6A2")) //线条设置
            lineOptions.jointType(JointType.ROUND)
            lineOptions.width(15f)
            map.clear()
            map.addPolyline(lineOptions)

            status = orderModel?.status
            if (status == 1) {
                hasDrawDriverToStart = true
            } else {
                hasDrawStartToEnd = true
            }

            if (decodedPath.size > 2) {
                zoomRoute(map, decodedPath)
                if (status == 1) {
//                    map.addMarker(
//                        MarkerOptions().position(decodedPath[0]).icon(
//                            BitmapDescriptorFactory.fromResource(R.drawable.ic_locate_current)
//                        )
//                    )
                } else {
                    map.addMarker(
                        MarkerOptions().position(decodedPath[0]).icon(
                            BitmapDescriptorFactory.fromResource(R.drawable.ic_start_point)
                        )
                    )
                }

                map.addMarker(
                    MarkerOptions().position(decodedPath[decodedPath.size - 1]).icon(
                        if (status == 1)
                            BitmapDescriptorFactory.fromResource(R.drawable.ic_start_point)
                        else
                            BitmapDescriptorFactory.fromResource(R.drawable.ic_end_point)
                    )
                )
                map.setOnCameraIdleListener { }
            }
        })
    }

    /**
     * Zooms a Route (given a List of LalLng) at the greatest possible zoom level.
     *
     * @param googleMap: instance of GoogleMap
     * @param lstLatLngRoute: list of LatLng forming Route
     */
    private fun zoomRoute(googleMap: GoogleMap?, lstLatLngRoute: List<LatLng>?) {

        if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return

        val boundsBuilder = LatLngBounds.Builder()
        for (latLngPoint in lstLatLngRoute)
            boundsBuilder.include(latLngPoint)

        val routePadding = 100
        val latLngBounds = boundsBuilder.build()

        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding))
    }


    override fun onResume() {
        super.onResume()
//        val mapFragment = supportFragmentManager
//            .findFragmentById(R.id.map) as SupportMapFragment?
//        mapFragment?.getMapAsync(this)

        startTimer()
    }

    override fun onPause() {
        super.onPause()

        stopTimer()
    }

    private fun startTimer() {
        timer = Timer()
        val task = object : TimerTask() {
            override fun run() {
                val currentLatLng = LocationUtil.getInstance().getCurrentLoc()
                if (null != currentLatLng) {
                    val startLat = orderModel?.startCoordinates?.latitude ?: 0.0
                    val startLng = orderModel?.startCoordinates?.longitude ?: 0.0
                    if (startLat != 0.0 && startLng != 0.0) {
                        val start = LatLng(startLat, startLng)
                        val status = orderModel?.status
                        if (status == 1) {
                            drawDriverToStart(currentLatLng, start)
                        } else {
                            val endLat = orderModel?.endCoordinates?.latitude ?: 0.0
                            val endLng = orderModel?.endCoordinates?.longitude ?: 0.0

                            if (startLat != 0.0 && startLng != 0.0 && endLat != 0.0 && endLng != 0.0) {
                                val end = LatLng(endLat, endLng)
                                drawStartToEnd(start, end)
                            }
                        }
                    }

                    drawDriverLocation(currentLatLng)
                }
            }
        }
        timer?.schedule(task, 0, 5 * 1000L)
    }

    private fun stopTimer() {
        timer?.cancel()
        timer = null
    }

    private fun drawDriverToStart(driver: LatLng, start: LatLng) {
        if (!hasDrawDriverToStart) {//是否绘制过司机到起点的路线
            queryRoute(
                driver,
                start
            )

        }
    }

    private fun drawStartToEnd(start: LatLng, end: LatLng) {
        if (!hasDrawStartToEnd) {
            queryRoute(
                start,
                end
            )
        }
    }

    private var hasDrawDriverToStart = false
    private var hasDrawStartToEnd = false
    private var driverMarker: Marker? = null
    private var isMapReady = false

    private fun drawDriverLocation(latlng: LatLng) {
        if (isMapReady) {
            runOnUiThread {
                driverMarker?.remove()
                driverMarker = mMap.addMarker(
                    MarkerOptions().position(latlng)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_red_car))
                )
            }
        }
    }

    private fun isOrderInProgress(status: Int, startTime: String): Boolean {
        if (status == 0 && !startTime.isNullOrEmpty()) {
            val startDate: Date = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime)

            var nowTime: Date = Date()
            var timeGap = startDate.time - nowTime.time
            if (timeGap > 0) {
                return false
            }
        }
        return true
    }

    /**谷歌境外坐标系 (WGS-84) 转 火星坐标系(GCJ-02)的转换*/
    private fun convert(latlng: LatLng) =
        GPSConverterUtils.gps84_To_Gcj02(latlng.latitude, latlng.longitude)
}